package cn.kent.simple;

import java.util.LinkedList;

/**
 * 101. 对称二叉树
 */
public class IsSymmetric {
    public static void main(String[] args) {

    }

    /**
     * 思路：根节点的左子树和右子树一一对比 -> 递归
     */
    public static boolean isSymmetric(TreeNode root) {
        // 递归
        // return check(root.left, root.right);
        // 迭代
        return check2(root, root);
    }

    /**
     * 迭代方法
     */
    private static boolean check2(TreeNode u, TreeNode v) {
        LinkedList<TreeNode> q = new LinkedList<>();
        q.offer(u);
        q.offer(v);
        while (!q.isEmpty()) {
            u = q.poll();
            v = q.poll();
            if (u == null && v == null) {
                continue;
            }
            if ((u == null || v == null) || (u.val != v.val)) {
                return false;
            }

            q.offer(u.left);
            q.offer(v.right);

            q.offer(u.right);
            q.offer(v.left);
        }
        return true;
    }

    /**
     * 递归
     */
    private static boolean check(TreeNode p, TreeNode q) {
        if (p == null && q == null) {
            return true;
        }
        if (p == null || q == null) {
            return false;
        }
        // if (p.val == q.val) {
        //     if (check(p.left, q.right)) {
        //         if (check(p.right, q.left)) {
        //             return true;
        //         }
        //     }
        // }
        // return false;
        return p.val == q.val && check(p.left, q.right) && check(p.right, q.left);
    }


    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
